package soulkun.library.custom.view

import android.content.Context
import android.graphics.Canvas
import android.graphics.Paint
import android.text.Layout
import android.text.StaticLayout
import android.text.TextPaint
import android.util.AttributeSet
import android.widget.TextView

/**
 * 多行文字居中的TextView，只用于纯文字且无hint
 */
class MultiLinesCenterTextView : androidx.appcompat.widget.AppCompatTextView {

    private lateinit var staticLayout: StaticLayout

    constructor(context: Context) : super(context)

    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs)

    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(
        context,
        attrs,
        defStyleAttr
    )

    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        super.onSizeChanged(w, h, oldw, oldh)
        initView()
    }

    private fun initView() {
        val textPaint = TextPaint(Paint.ANTI_ALIAS_FLAG)
        textPaint.textSize = textSize
        textPaint.color = currentTextColor
        staticLayout =
            StaticLayout(text, textPaint, width, Layout.Alignment.ALIGN_CENTER, 1.0f, 0.0f, false)
    }

    override fun onDraw(canvas: Canvas?) {
        staticLayout.draw(canvas)
    }

}